<?php

namespace core\base;


use yii\db\ActiveRecord;
use yii\helpers\Inflector;
use yii\helpers\StringHelper;

class BaseModel extends ActiveRecord
{

    public static function tableName()
    {
        $tableName = StringHelper::basename(get_called_class());
        $tableName = Inflector::camel2id(substr($tableName, 3), '_');
        return $tableName;
    }

    /**
     * 根据条件查询一条数据
     * @param $condition
     * @return array|null|\yii\db\ActiveRecordInterface
     */
    public static function findOneByCondition($condition)
    {
        $data = static::findByCondition($condition)->asArray()->one();
        return $data;
    }

    /**
     * 根据条件查询数据
     * @param $condition
     * @return array
     */
    public static function findAllByCondition($condition)
    {
        $data = static::findByCondition($condition)->asArray()->all();
        return $data;
    }

    /**
     * 批量插入
     * @param $data
     * @return bool|int
     */
    public static function batchInsert($data)
    {
        if (!empty($data)) {
            return self::getDb()->createCommand()->batchInsert(self::tableName(), array_keys(current($data)), $data)->execute();
        } else {
            return false;
        }
    }

    public static function deleteByPk($pk)
    {
        if (!is_array($pk)) {
            $pk = [$pk];
        }

        self::deleteAll([self::getUniquePk() => $pk]);
    }

    public static function updateByPk($pk, $attributes = array())
    {
        if (empty($attributes)) {
            return;
        }
        self::updateAll($attributes, [self::getUniquePk() => $pk]);
    }

    public static function getUniquePk()
    {
        $pkArr = self::primaryKey();
        if (count($pkArr) != 1) {
            throw new \Exception('主键', 500);
        }
        return $pkArr[0];
    }

    public function getFirstPk()
    {
        return array_shift(self::primaryKey());
    }

    private function findByPkInternal($pk, $asArray)
    {
        return self::find()
            ->asArray($asArray)
            ->where([$this->getFirstPk() => $pk]);
    }

    public function findOneByPk($pk, $asArray = false)
    {
        return $this->findByPkInternal($pk, $asArray)->one();
    }
}